package com.goa.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * netty服务器，主要用于与客户端通讯
 */
public class NettyServer {

    private final static Logger log = LoggerFactory.getLogger(NettyServer.class);

    private final int port; //监听端口
 
 
    public NettyServer(int port) {
        this.port = port;
    }
 
    //编写run方法，处理客户端的请求
    public void run() throws Exception {
 
        //创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8); //8个NioEventLoop
 
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //获取到pipeline
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new IdleStateHandler(30,0,0, TimeUnit.SECONDS));
                            //token拦截器
//                            pipeline.addLast(new TokenAuthHandler());
                            pipeline.addLast(new NettyServerHandler());
 
                        }
                    });
            log.info("netty服务器启动成功（port:" + port + "）......");
            System.out.println("netty服务器启动成功（port:" + port + "）......");
//            ChannelFuture channelFuture = b.bind(port).sync();
            ChannelFuture channelFuture = b.bind("0.0.0.0", port).sync();  // 绑定到所有网络接口
            //监听关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
 
    }

}